package com.haodai.agency.net;

import android.util.Base64;

import com.haodai.agency.application.MyApplication;
import com.haodai.agency.products.bean.request.UploadImgBean;
import com.haodai.agency.save.SaveSharedPreferences;
import com.haodai.agency.utils.AESCrypt;
import com.haodai.agency.utils.Logs;
import com.haodai.agency.utils.MD5Util;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.concurrent.TimeUnit;

import okhttp3.Cache;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * Created by Administrator on 2017/4/1.
 */

public class UploadUtil{

    private static final String TAG = UploadUtil.class.getSimpleName();

    //设置缓存目录
    private static File cacheDirectory = new File(MyApplication.CONTEXT.getApplicationContext().getCacheDir().getAbsolutePath(), "MyCache");
    private static Cache cache =  new Cache(cacheDirectory, 10 * 1024 * 1024);
    private static final MediaType MEDIA_TYPE_PNG = MediaType.parse("image/png");
    //设置超时时间及缓存
    private static OkHttpClient.Builder builder = new OkHttpClient.Builder()
            .connectTimeout(15, TimeUnit.SECONDS)
            .writeTimeout(20, TimeUnit.SECONDS)
            .readTimeout(20, TimeUnit.SECONDS)
            .cache(cache);

    private static UploadUtil instance;
    public static UploadUtil getInstance(){
        if(instance==null)
            instance=new UploadUtil();
        return instance;
    }

    private static OkHttpClient mOkHttpClient=builder.build();

    public void upload(List<String> lists, String url, Object t, final CallLisener callLisener){

        MultipartBody.Builder mbody=new MultipartBody.Builder().setType(MultipartBody.FORM);

        for(String path:lists){
            File file=new File(path);
            if(file.exists()){
                mbody.addPart(MultipartBody.Part.createFormData("img[]",path, RequestBody.create(MEDIA_TYPE_PNG,file)));
            }
        }
        Logs.e(TAG,">>>>>>data、原值>>>>" + t.toString());
        String data= AESCrypt.getInstance().encrypt(t.toString());

        String base64Data = "";
        String sign = "";
        String temp=System.currentTimeMillis()/1000+"";
        String token= SaveSharedPreferences.getToken();
        try {
            base64Data = new String(Base64.encode((t.toString() + token + temp).trim().getBytes(),
                    Base64.DEFAULT), "UTF-8");
            sign=AESCrypt.SIGN_KEY + base64Data.trim().replace("\n","") + AESCrypt.SIGN_KEY;
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        mbody.addFormDataPart("data",data);
        Logs.e(TAG,">>>data>>>>>" + data);
        mbody.addFormDataPart("sign", MD5Util.myMd5(sign));
        mbody.addFormDataPart("token",token);
        mbody.addFormDataPart("timestamp",temp);


        RequestBody requestBody =mbody.build();
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();

        mOkHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                if(callLisener!=null)
                    callLisener.onFailure(call,e);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if(callLisener!=null)
                    callLisener.onSuccess(call,response);
            }
        });
    }

    public interface CallLisener{
        void onSuccess(Call call, Response response);
        void onFailure(Call call, IOException e);
    }
}
